package com.lagou.duration

import scala.collection.mutable.ArrayBuffer
import scala.io.{BufferedSource, Source}

case class UserInfo(userName: String, location: String, startTime: Int, duration: Int)

object DurationStatistics {
    def main(args: Array[String]): Unit = {
        val recordInfo: BufferedSource = Source.fromFile("user.data", "UTF-8")
        val lines: Iterator[String] = recordInfo.getLines()

        val userInfos: ArrayBuffer[UserInfo] = new ArrayBuffer[UserInfo]()

        for (line <- lines) {
            val fields: Array[String] = line.split(",")
            val userInfo: UserInfo = new UserInfo(fields(0), fields(1), fields(2).toInt, fields(3).toInt)
            userInfos.append(userInfo)
        }

        val userInfoMap: Map[String, ArrayBuffer[UserInfo]] = userInfos.groupBy(u => u.userName + "," + u.location)
        val sortUserMap: Map[String, ArrayBuffer[UserInfo]] = userInfoMap.mapValues(m => m.sortBy(s => s.startTime))

        var startTime = 0

        val result: Map[String, Int] = sortUserMap.mapValues(s => {
            startTime = s.head.startTime
            val sum: Int = s.map(t => t.duration).sum
            sum
        })
        result.foreach {
            case (userInfo, sum) => println(s"$userInfo, $startTime, $sum")
        }
    }
}
